//
//  DeliveryViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-11-14.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "DeliveryViewController.h"
#import "DeliveryDetailViewController.h"
#import "AddressManageViewController.h"
#import "NetServiseCommonData.h"
#import "AddressModel.h"
#import "RegisterHelper.h"

@interface DeliveryViewController ()<UITableViewDelegate,UITableViewDataSource,deliveryDetailViewDelegate>
{
    UITableView *addressTableView;
}
@end

@implementation DeliveryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleView:@"选择收货地址"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _dataArray = [[NSMutableArray alloc]initWithCapacity:1];

    //获取收货地址
    [self getAddressData];
    
    
    _textLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth/2-200/2, (kHeight-kTabBarHeight-40)/2, 200, 20)];
    _textLabel.text = @"没有收货地址，添加一个吧～";
    _textLabel.font = [UIFont systemFontOfSize:14.0f];
    _textLabel.textColor = UIColorFromRGB(0x9fa0a0);
    _textLabel.alpha = 0.0;
    [self.view addSubview:_textLabel];
    
    addressTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 70*_dataArray.count)];
    addressTableView.dataSource = self;
    addressTableView.delegate = self;
    addressTableView.scrollEnabled = YES;
    [self.view addSubview:addressTableView];

    [self setRightButton:@"地址管理" sel:@selector(addressManageAction) viewController:self];
    
    NSInteger y;
    if (IS_4_INCH_SCREEN) {
        y = 450;
    }else{
        y = 360;
    }
    UIButton *addButton = [[UIButton alloc]initWithFrame:CGRectMake(10, kHeight-64-50, kWidth-20, 40)];
    [addButton setTitle:@"添加新地址" forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton setBackgroundImage:[UIImage imageNamed:@"register_login"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addbuttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:addButton];
    

    // Do any additional setup after loading the view.
}

#pragma mark getAddressData  获取收货地址
-(void)getAddressData{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userId = [RegisterHelper shareHelper].userId;
    SetValueForKey(params, userId, @"userId");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kAddressList
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             DLog(@"error %@",response.errorMessage);
                         }else{
                             
                             [_dataArray removeAllObjects];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSArray *list = [responseDic objectForKey:@"list"];
                             DLog(@"数据列表:%@",list);
                             
                             for (NSDictionary *dic in list) {
                                 AddressModel *addressModel = [[AddressModel alloc]initWithAddressInfo:dic];
                                 [_dataArray addObject:addressModel];
                             }
                             
                             if(_dataArray.count == 0){
                                 addressTableView.alpha = 0;
                                 _textLabel.alpha = 1;
                             }else{
                                 addressTableView.height =70*_dataArray.count;
                                 addressTableView.alpha = 1;
                                 _textLabel.alpha = 0;
                             }
                             [addressTableView reloadData];
                             
                         }
                     }];
}

-(void)addbuttonAction{
    
    DeliveryDetailViewController *deliveryDetailVC = [[DeliveryDetailViewController alloc]init];
    deliveryDetailVC.hidesBottomBarWhenPushed = YES;
    deliveryDetailVC.delegate = self;
    deliveryDetailVC.isModify = NO;
    [self.navigationController pushViewController:deliveryDetailVC animated:YES];
}

#pragma mark deliveryDetailVC --delegate
-(void)commitAddress{
    
    //获取收货地址
    [self getAddressData];
    [addressTableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"shareCellIdentitfer"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shareCellIdentitfer"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        
       UILabel *address = [[UILabel alloc]initWithFrame:CGRectMake(40,10,260, 60)];
        address.numberOfLines = 0;
        address.tag = 100;
        address.font = [UIFont systemFontOfSize:14.0f];
        address.backgroundColor = [UIColor clearColor];
        address.textColor = UIColorFromRGB(0x9fa0a0);
        [cell.contentView addSubview:address];
      
    }
    
       AddressModel *addressModel = _dataArray[indexPath.row];
    
    UILabel *addressLabel = (UILabel *)[cell.contentView viewWithTag:100];
    _addressText = [NSString stringWithFormat:@"%@  %@%@%@%@%@%@",addressModel.name,addressModel.phone,addressModel.province,addressModel.city,addressModel.area,addressModel.address,addressModel.code];
    addressLabel.text = _addressText;
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddressModel *addressModel = _dataArray[indexPath.row];
    NSString *address = [NSString stringWithFormat:@"%@  %@%@%@%@%@%@",addressModel.name,addressModel.phone,addressModel.province,addressModel.city,addressModel.area,addressModel.address,addressModel.code];
    
    [RegisterHelper shareHelper].addressModel = addressModel;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(commitAddress:)]) {
        [self.delegate commitAddress:address];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}


//地址管理
-(void)addressManageAction{
    
    AddressManageViewController *addressManageVC = [[AddressManageViewController alloc]init];
    addressManageVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addressManageVC animated:YES];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //获取收货地址
    [self getAddressData];
    [addressTableView reloadData];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
